using LiJ.Common.Core;
using LiJ.Common.Core.Enums;
using System;
using System.IO;
using System.Xml.Serialization;

namespace LiJ.Common.Plugs.DirConfigPlug
{
	/// <inheritdoc />
	/// <summary>
	/// 默认配置处理
	/// </summary>
	public class DefaultDirConfigPlug : IDirConfigPlug
	{
		private static readonly string DefaultPath;

		static DefaultDirConfigPlug()
		{
            DefaultPath = AppContext.BaseDirectory;
		}

		/// <inheritdoc />
		/// <summary>
		/// 设置字典配置信息
		/// </summary>
		/// <typeparam name="TConfig"></typeparam>
		/// <param name="key"></param>
		/// <param name="dirConfig"></param>
		/// <returns></returns>
		public ResultMo SetDirConfig<TConfig>(string key, TConfig dirConfig) where TConfig : class, new()
		{
			if (string.IsNullOrEmpty(key))
			{
				throw new ArgumentNullException("key", "配置键值不能为空！");
			}
			if (dirConfig == null)
			{
				throw new ArgumentNullException("dirConfig", "配置信息不能为空！");
			}
			string text = DefaultPath + "\\" + "Config";
			FileStream fileStream = null;
			try
			{
				if (!Directory.Exists(text))
				{
					Directory.CreateDirectory(text);
				}
				fileStream = new FileStream(text + "\\" + key + ".config", FileMode.Create, FileAccess.Write);
				new XmlSerializer(typeof(TConfig)).Serialize(fileStream, dirConfig);
				return new ResultMo();
			}
			finally
			{
			    fileStream?.Dispose();
			}
		}

		/// <inheritdoc />
		/// <summary>
		///   获取字典配置
		/// </summary>
		/// <typeparam name="TConfig"></typeparam>
		/// <param name="key"></param>
		/// <returns></returns>
		public TConfig GetDirConfig<TConfig>(string key) where TConfig : class, new()
		{
			if (string.IsNullOrEmpty(key))
			{
				throw new ArgumentNullException("key", "配置键值不能为空！");
			}
			string str = DefaultPath + "\\" + "Config";
			FileStream fileStream = null;
			try
			{
				string path = str + "\\" + key + ".config";
				if (!File.Exists(path))
				{
					return null;
				}
				fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
				return (TConfig)new XmlSerializer(typeof(TConfig)).Deserialize(fileStream);
			}
			finally
			{
			    fileStream?.Dispose();
			}
		}

		/// <inheritdoc />
		/// <summary>
		///  移除配置信息
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public ResultMo RemoveDirConfig(string key)
		{
			string path = DefaultPath + "\\" + "Config" + "\\" + key + ".config";
			if (!File.Exists(path))
			{
				return new ResultMo(ResultTypes.InnerError, "移除字典配置时出错");
			}
			File.Delete(path);
			return new ResultMo();
		}
	}
}
